#!/usr/bin/env python3
"""
独立的镜像管理工具 - 不依赖模块导入
"""

import argparse
import subprocess
import sys
import json
from pathlib import Path

class MirrorManager:
    def __init__(self, repo_path="."):
        self.repo_path = Path(repo_path).absolute()
    
    def run_git(self, args, check=False):
        """运行 git 命令"""
        try:
            cmd = ["git", "-C", str(self.repo_path)] + args
            result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
            return result.returncode == 0, result.stdout.strip()
        except Exception as e:
            return False, str(e)
    
    def check_mirror(self, mirror_url):
        """检查镜像可用性"""
        print(f"🔍 检查镜像: {mirror_url}")
        success, output = self.run_git(["ls-remote", mirror_url])
        if success:
            print("   ✅ 可用")
            return True
        else:
            print("   ❌ 不可用")
            return False
    
    def setup_mirror(self, original_url, mirror_url):
        """设置镜像规则"""
        if self.check_mirror(mirror_url):
            config_name = f"url.{mirror_url}.insteadOf"
            success, _ = self.run_git(["config", "--local", config_name, original_url])
            if success:
                print(f"   ✅ 配置成功: {original_url} → {mirror_url}")
                return True
            else:
                print(f"   ❌ 配置失败")
                return False
        return False

def main():
    parser = argparse.ArgumentParser(description='镜像管理工具')
    subparsers = parser.add_subparsers(dest='command', help='子命令')
    
    # check 命令
    check_parser = subparsers.add_parser('check', help='检查镜像')
    check_parser.add_argument('mirror_url', help='镜像URL')
    check_parser.add_argument('--repo', default='.', help='仓库路径')
    
    # setup 命令
    setup_parser = subparsers.add_parser('setup', help='设置镜像')
    setup_parser.add_argument('original_url', help='原始URL')
    setup_parser.add_argument('mirror_url', help='镜像URL')
    setup_parser.add_argument('--repo', default='.', help='仓库路径')
    
    # batch 命令
    batch_parser = subparsers.add_parser('batch', help='批量设置')
    batch_parser.add_argument('--config', default='mirrors.json', help='配置文件')
    batch_parser.add_argument('--repo', default='.', help='仓库路径')
    
    args = parser.parse_args()
    
    if not args.command:
        parser.print_help()
        return
    
    manager = MirrorManager(args.repo)
    
    if args.command == 'check':
        success = manager.check_mirror(args.mirror_url)
        sys.exit(0 if success else 1)
    
    elif args.command == 'setup':
        success = manager.setup_mirror(args.original_url, args.mirror_url)
        sys.exit(0 if success else 1)
    
    elif args.command == 'batch':
        print("批量设置功能待实现")
        # 这里可以添加从配置文件读取和批量设置的逻辑

if __name__ == '__main__':
    main()
